package com.autoool;


import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author sam
 * 2021/6/24 20:04
 */
public class CustomClassLoader extends ClassLoader {

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Class<?> clazz = new CustomClassLoader().findClass("Hello");
        Method method = clazz.getDeclaredMethod("hello");
        Object object = clazz.newInstance();
        method.invoke(object);

    }

    private static final String classPath = "week1/src/main/resources/Hello.xlass";

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            InputStream inputStream = new FileInputStream(classPath);

            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int n;
            while (-1 != (n = inputStream.read(buffer))) {
                output.write(buffer, 0, n);
            }
            byte[] bytes = output.toByteArray();
            byte[] realBytes = new byte[bytes.length];
            for (int i = 0; i < bytes.length; i++) {
                realBytes[i] = (byte) (255 - (int) bytes[i]);
            }
            return defineClass(name, realBytes, 0, realBytes.length);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return super.findClass(name);
    }

}
